﻿namespace SPTaxonomyClient.Taxonomy
{
	using System.Collections.Generic;
	using System.Linq;
	using System.Xml.Linq;

	/// <summary>
	/// A term object issued from a <see cref="TermSet"/>
	/// </summary>
	public class Term
	{
		private IList<TermDefinition> _definitions;

		/// <summary>
		/// The guid identifying uniquely the term in the TermSet.
		/// </summary>
		public string Id { get; set; }

		/// <summary>
		/// The name of the term is the first <see cref="TermDefinition"/> object that is flagged as default for the current language.
		/// </summary>
		public string Name
		{
			get
			{
				return (from def in Definitions
						where def.IsDefaultForLanguage
						select def.Value).FirstOrDefault();
			}
		}

		/// <summary>
		/// The <see cref="TermSet"/> that the Term belongs to.
		/// </summary>
		public TermSet ParentTermSet { get; set; }

		/// <summary>
		/// The Term that this Term belongs to, if any. Null if there isn't.
		/// </summary>
		public Term ParentTerm { get; set; }

		/// <summary>
		/// The labels that represent this Term in different languages. At least one, flagged as default for the current language.
		/// </summary>
		public IList<TermDefinition> Definitions
		{
			get
			{
				return _definitions ?? (_definitions = new List<TermDefinition>());
			}
		}

		/// <summary>
		/// Initialize an empty Term
		/// </summary>
		public Term()
		{

		}

		/// <summary>
		/// Initializes the Term from an XML element that respects the format exposed by TaxonomyClientService.asmx.
		/// </summary>
		/// <param name="xTerm">An XML "T" element.</param>
		public Term(XElement xTerm)
		{
			if (xTerm.Name != "T")
			{
				xTerm = xTerm.Element("T");
			}
			// ReSharper disable PossibleNullReferenceException
			Id = xTerm.Attribute("a9").Value;
			// ReSharper restore PossibleNullReferenceException

			foreach (XElement termDef in xTerm.Descendants("TL"))
			{
				Definitions.Add(
					new TermDefinition
					{
						// ReSharper disable PossibleNullReferenceException
						IsDefaultForLanguage = bool.Parse(termDef.Attribute("a31").Value),
						Value = termDef.Attribute("a32").Value
						// ReSharper restore PossibleNullReferenceException
					});
			}
		}
	}
}
